/**
 * Created by jiachenpan on 16/11/18.
 */

export function parseTime(date, fmt) {
    if (date == undefined || date == '' || date == null) {
        return ''
    }
    if(typeof date=='string'){
        date = date.replace('.','-').replace('.','-').replace('.','-');
    }

    date = date == undefined ? new Date() : new Date(date);
    //date = typeof date == 'number' ? new Date(date) : date;
    fmt = fmt || 'yyyy-MM-dd HH:mm:ss';
  let obj =
        {
            'y': date.getFullYear(), // 年份，注意必须用getFullYear
            'M': date.getMonth() + 1, // 月份，注意是从0-11
            'd': date.getDate(), // 日期
            'q': Math.floor((date.getMonth() + 3) / 3), // 季度
            'w': date.getDay(), // 星期，注意是0-6
            'H': date.getHours(), // 24小时制
            'h': date.getHours() % 12 == 0 ? 12 : date.getHours() % 12, // 12小时制
            'm': date.getMinutes(), // 分钟
            's': date.getSeconds(), // 秒
            'S': date.getMilliseconds() // 毫秒
        };
  let week = ['日', '一', '二', '三', '四', '五', '六'];
    let i,j,len;
    for (i in obj) {
        fmt = fmt.replace(new RegExp(i + '+', 'g'), function (m) {
            let val = obj[i] + '';
            if (i == 'w') return (m.length > 2 ? '星期' : '周') + week[val];
            for (j = 0, len = val.length; j < m.length - len; j++) val = '0' + val;
            return m.length == 1 ? val : val.substring(val.length - m.length);
        });
    }
    return fmt;
}

  /*

    以当前日期为基础。追加天数
    d:要追加的天数
    */
    export function isSameDay(date1, date2) {
		if(date1 == null || date2 == null) return false;
        var day1 = new Date(date1).getDate();
        var day2 = new Date(date2).getDate();
		return day1 == day2;
    }

  /*

    以当前日期为基础。追加天数
    d:要追加的天数
    */
    export function isSameYear(date1, date2) {
		if(date1 == null || date2 == null) return false;
        var year1 = new Date(date1).getFullYear();
        var year2 = new Date(date2).getFullYear();
		return year1 == year2;
    }
  /*

    以当前日期为基础。追加天数
    d:要追加的天数
    */
    export function addDays(date, d) {
		if(date == null) return null;
        var Year = date.getFullYear();  //当前年
        var Month = date.getMonth() + 1; //当前月
        var Day = date.getDate(); //当前日
        var dayNumber = new Date(Year, Month + 1, 0).getDate(); //当月天数

        for (var i = 0; i < d; i++) {
            Day++;
            if (Day > dayNumber) {
                Day = 1;
                Month++;
                if (Month > 12) {
                    Month = 1;
                    Year++;
                }
            }
        }
        return new Date(Year, Month - 1, Day);
    }
/**
 * 价格显示格式化 1,231.00元
 * @param money 价格值
 * @param precision 精度
 * @param isUnit 是否需要单位(人民币：元、万元),默认不写
 * @param unit 单位, 不填则在前面加'￥'
 * @returns {string}
 */
export function fmMoney(money, precision ,isUnit) {
    if(money === undefined || money === null || money.toString().replace(/^\s+|\s+$/g, '') === '') money = 0;
    let isMinus = (money+'').indexOf('-')>-1
    precision = precision || 0;
    if(precision > 2) precision = 2;
    isUnit = isUnit==undefined?false :isUnit;
    let unit = "",i;
    if(isUnit) unit = "￥"
    money = parseFloat((money + "").replace(/[^\d\.]/g, ""))
    if(money == 0){
      money = "0.";
      for(i = 0; i < precision; i ++ ) {
        money+="0";
      }
      return unit + money;
    }
    money = money.toFixed(precision) + "";
    //_integer -- 整数部分，_dec -- 小数部分, _comma--每三位数用逗号分隔
    let _integer = money.split(".")[0].split("").reverse(),
        _dec     = "",
        _comma   = "";
    if(precision>0){
      _dec = "." + money.split(".")[1];
    }
    // if(_integer.length>4) {
    //   //过万元
    //   if(isUnit) unit = "万元";
    //   else unit = "W";
    //   return fmMoney(money / 10000, 2, false) + unit;
    // }
    for(i = 0; i < _integer.length; i ++ )
    {
      _comma += _integer[i] + ((i + 1) % 3 == 0 && (i + 1) != _integer.length ? "," : "");
    }
    return unit + (isMinus?'-':'') + _comma.split("").reverse().join("") + _dec;
}

export function floatAdd(arg1,arg2) {
    let r1,r2,m;
    try{r1=arg1.toString().split(".")[1].length}catch(e){r1=0}
    try{r2=arg2.toString().split(".")[1].length}catch(e){r2=0}
    let d = Math.max(r1,r2);
    m=Math.pow(10,d);
    return ((arg1*m+arg2*m)/m).toFixed(d);
}
export function floatSub(arg1,arg2) {
    let r1,r2,m,n;
    try{r1=arg1.toString().split(".")[1].length}catch(e){r1=0}
    try{r2=arg2.toString().split(".")[1].length}catch(e){r2=0}
    m=Math.pow(10,Math.max(r1,r2));
    //动态控制精度长度
    n = Math.max(r1,r2);
    //n=(r1=r2)?r1:r2;
    return ((arg1*m-arg2*m)/m).toFixed(n);
}
export function floatMul(arg1,arg2) {
    let m=0,s1=arg1.toString(),s2=arg2.toString();
    try{m+=s1.split(".")[1].length}catch(e){}
    try{m+=s2.split(".")[1].length}catch(e){}
    return Number(s1.replace(".",""))*Number(s2.replace(".",""))/Math.pow(10,m);
}
export function floatDiv(arg1,arg2) {
    let t1=0,t2=0,r1,r2;
    try{t1=arg1.toString().split(".")[1].length}catch(e){}
    try{t2=arg2.toString().split(".")[1].length}catch(e){}
    r1=Number(arg1.toString().replace(".",""));
    r2=Number(arg2.toString().replace(".",""));
    return (r1/r2)*Math.pow(10,t2-t1);
}

export function formatTime(time, option) {
  time = +time * 1000
  const d = new Date(time)
  const now = Date.now()

  const diff = (now - d) / 1000

  if (diff < 30) {
    return '刚刚'
  } else if (diff < 3600) {
    // less 1 hour
    return Math.ceil(diff / 60) + '分钟前'
  } else if (diff < 3600 * 24) {
    return Math.ceil(diff / 3600) + '小时前'
  } else if (diff < 3600 * 24 * 2) {
    return '1天前'
  }
  if (option) {
    return parseTime(time, option)
  } else {
    return (
      d.getMonth() +
      1 +
      '月' +
      d.getDate() +
      '日' +
      d.getHours() +
      '时' +
      d.getMinutes() +
      '分'
    )
  }
}

// 格式化时间
export function getQueryObject(url) {
  url = url == null ? window.location.href : url
  const search = url.substring(url.lastIndexOf('?') + 1)
  const obj = {}
  const reg = /([^?&=]+)=([^?&=]*)/g
  search.replace(reg, (rs, $1, $2) => {
    const name = decodeURIComponent($1)
    let val = decodeURIComponent($2)
    val = String(val)
    obj[name] = val
    return rs
  })
  return obj
}

/**
 *get getByteLen
 * @param {Sting} val input value
 * @returns {number} output value
 */
export function getByteLen(val) {
  let len = 0,i;
  for (i = 0; i < val.length; i++) {
    if (val[i].match(/[^\x00-\xff]/gi) != null) {
      len += 1
    } else {
      len += 0.5
    }
  }
  return Math.floor(len)
}

export function cleanArray(actual) {
  const newArray = []
  for (let i = 0; i < actual.length; i++) {
    if (actual[i]) {
      newArray.push(actual[i])
    }
  }
  return newArray
}

export function param(json) {
  if (!json) return ''
  return cleanArray(
    Object.keys(json).map(key => {
      if (json[key] === undefined) return ''
      return encodeURIComponent(key) + '=' + encodeURIComponent(json[key])
    })
  ).join('&')
}

export function param2Obj(url) {
  const search = url.split('?')[1]
  if (!search) {
    return {}
  }
  return JSON.parse(
    '{"' +
      decodeURIComponent(search)
        .replace(/"/g, '\\"')
        .replace(/&/g, '","')
        .replace(/=/g, '":"') +
      '"}'
  )
}

export function html2Text(val) {
  const div = document.createElement('div')
  div.innerHTML = val
  return div.textContent || div.innerText
}

export function objectMerge(target, source) {
  /* Merges two  objects,
     giving the last one precedence */

  if (typeof target !== 'object') {
    target = {}
  }
  if (Array.isArray(source)) {
    return source.slice()
  }
  Object.keys(source).forEach(property => {
    const sourceProperty = source[property]
    if (typeof sourceProperty === 'object') {
      target[property] = objectMerge(target[property], sourceProperty)
    } else {
      target[property] = sourceProperty
    }
  })
  return target
}

export function toggleClass(element, className) {
  if (!element || !className) {
    return
  }
  let classString = element.className
  const nameIndex = classString.indexOf(className)
  if (nameIndex === -1) {
    classString += '' + className
  } else {
    classString =
      classString.substr(0, nameIndex) +
      classString.substr(nameIndex + className.length)
  }
  element.className = classString
}

export const pickerOptions = [
  {
    text: '今天',
    onClick(picker) {
      const end = new Date()
      const start = new Date(new Date().toDateString())
      end.setTime(start.getTime())
      picker.$emit('pick', [start, end])
    }
  },
  {
    text: '最近一周',
    onClick(picker) {
      const end = new Date(new Date().toDateString())
      const start = new Date()
      start.setTime(end.getTime() - 3600 * 1000 * 24 * 7)
      picker.$emit('pick', [start, end])
    }
  },
  {
    text: '最近一个月',
    onClick(picker) {
      const end = new Date(new Date().toDateString())
      const start = new Date()
      start.setTime(start.getTime() - 3600 * 1000 * 24 * 30)
      picker.$emit('pick', [start, end])
    }
  },
  {
    text: '最近三个月',
    onClick(picker) {
      const end = new Date(new Date().toDateString())
      const start = new Date()
      start.setTime(start.getTime() - 3600 * 1000 * 24 * 90)
      picker.$emit('pick', [start, end])
    }
  }
]

export function getTime(type) {
  if (type === 'start') {
    return new Date().getTime() - 3600 * 1000 * 24 * 90
  } else {
    return new Date(new Date().toDateString())
  }
}

export function debounce(func, wait, immediate) {
  let timeout, args, context, timestamp, result

  const later = function() {
    // 据上一次触发时间间隔
    const last = +new Date() - timestamp

    // 上次被包装函数被调用时间间隔last小于设定时间间隔wait
    if (last < wait && last > 0) {
      timeout = setTimeout(later, wait - last)
    } else {
      timeout = null
      // 如果设定为immediate===true，因为开始边界已经调用过了此处无需调用
      if (!immediate) {
        result = func.apply(context, args)
        if (!timeout) context = args = null
      }
    }
  }

  return function(...args) {
    context = this
    timestamp = +new Date()
    const callNow = immediate && !timeout
    // 如果延时不存在，重新设定延时
    if (!timeout) timeout = setTimeout(later, wait)
    if (callNow) {
      result = func.apply(context, args)
      context = args = null
    }

    return result
  }
}

/**
 * This is just a simple version of deep copy
 * Has a lot of edge cases bug
 * If you want to use a perfect deep copy, use lodash's _.cloneDeep
 */
export function deepClone(source) {
  if (!source && typeof source !== 'object') {
    throw new Error('error arguments', 'shallowClone')
  }
  const targetObj = source.constructor === Array ? [] : {}
  Object.keys(source).forEach(keys => {
    if (source[keys] && typeof source[keys] === 'object') {
      targetObj[keys] = deepClone(source[keys])
    } else {
      targetObj[keys] = source[keys]
    }
  })
  return targetObj
}

export function uniqueArr(arr) {
  return Array.from(new Set(arr))
}

export function isExternal(path) {
  return /^(https?:|mailto:|tel:)/.test(path)
}
//生成包含数字 字母  下划线的随机数
export function createRandom(len) {
    let str = "",arr = ['_','0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z'];
    for(let i=0; i<len; i++){
        let pos = Math.round(Math.random() * (arr.length-1));
        str += arr[pos];
    }
    return str;
}

/**
 * 分离文件扩展名
 * @param fileName 文件名称
 * @returns {string|string} 返回文件扩展名,没有返回null
 */
export function getFileSuffix(fileName) {
    let ext = null;
    if(fileName !== undefined && fileName !== null &&  fileName.toString().replace(/^\s+|\s+$/g, '') !== ''){
      let dotIndex = fileName.lastIndexOf('.');
      if(dotIndex>-1){
        ext = fileName.substring(dotIndex).replace('.','')
      }
    }
    return ext;
}
/**
 * 分离文件名称
 * @param fileName 文件名称
 * @returns {string|string} 返回无后缀文件名,没有返回原名称
 */
export function getNoSuffixFileName(fileName) {
    let ext = fileName;
    if(fileName !== undefined && fileName !== null &&  fileName.toString().replace(/^\s+|\s+$/g, '') !== ''){
      let dotIndex = fileName.lastIndexOf('.');
      if(dotIndex>-1){
        ext = fileName.substring(0,dotIndex)
      }
    }
    return ext;
}
export function createCode(length){
    //首先默认code为空字符串
    var code = '';
    //设置长度，这里看需求，我这里设置了4
    var codeLength = length || 4;
    //设置随机字符
    var random = new Array(0,1,2,3,4,5,6,7,8,9,'A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R', 'S','T','U','V','W','X','Y','Z');
    //循环codeLength 我设置的4就是循环4次
    for(var i = 0; i < codeLength; i++){
        //设置随机数范围,这设置为0 ~ 36
        var index = Math.floor(Math.random()*36);
        //字符串拼接 将每次随机的字符 进行拼接
        code += random[index];
    }
    //将拼接好的字符串赋值给展示的Value
    return code;
}

export function base64Encode(input) {
    const _keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
    var output = "", chr1, chr2, chr3, enc1, enc2, enc3, enc4, i = 0;
    input = utf8Encode(input);
    while (i < input.length) {
        chr1 = input.charCodeAt(i++);
        chr2 = input.charCodeAt(i++);
        chr3 = input.charCodeAt(i++);
        enc1 = chr1 >> 2;
        enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
        enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
        enc4 = chr3 & 63;
        if (isNaN(chr2)) {
            enc3 = enc4 = 64;
        } else if (isNaN(chr3)) {
            enc4 = 64;
        }
        output = output +
            _keyStr.charAt(enc1) + _keyStr.charAt(enc2) +
            _keyStr.charAt(enc3) + _keyStr.charAt(enc4);
    }
    return output;
}


export function base64Decode(input) {
    const _keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
    var output = "", chr1, chr2, chr3, enc1, enc2, enc3, enc4, i = 0;
    input = input.replace(/[^A-Za-z0-9\+\/\=]/g, "");
    while (i < input.length) {
        enc1 = _keyStr.indexOf(input.charAt(i++));
        enc2 = _keyStr.indexOf(input.charAt(i++));
        enc3 = _keyStr.indexOf(input.charAt(i++));
        enc4 = _keyStr.indexOf(input.charAt(i++));
        chr1 = (enc1 << 2) | (enc2 >> 4);
        chr2 = ((enc2 & 15) << 4) | (enc3 >> 2);
        chr3 = ((enc3 & 3) << 6) | enc4;
        output = output + String.fromCharCode(chr1);
        if (enc3 != 64) {
            output = output + String.fromCharCode(chr2);
        }
        if (enc4 != 64) {
            output = output + String.fromCharCode(chr3);
        }
    }
    output = utf8Decode(output);
    return output;
}

// private method for UTF-8 encoding
export function utf8Encode(string) {
    string = string.replace(/\r\n/g,"\n");
    var utftext = "";
    for (var n = 0; n < string.length; n++) {
        var c = string.charCodeAt(n);
        if (c < 128) {
            utftext += String.fromCharCode(c);
        } else if((c > 127) && (c < 2048)) {
            utftext += String.fromCharCode((c >> 6) | 192);
            utftext += String.fromCharCode((c & 63) | 128);
        } else {
            utftext += String.fromCharCode((c >> 12) | 224);
            utftext += String.fromCharCode(((c >> 6) & 63) | 128);
            utftext += String.fromCharCode((c & 63) | 128);
        }

    }
    return utftext;
}

// private method for UTF-8 decoding
export function utf8Decode (utftext) {
    var string = "", i = 0, c = 0, c1 = 0, c2 = 0, c3 = 0;
    while ( i < utftext.length ) {
        c = utftext.charCodeAt(i);
        if (c < 128) {
            string += String.fromCharCode(c);
            i++;
        } else if((c > 191) && (c < 224)) {
            c2 = utftext.charCodeAt(i+1);
            string += String.fromCharCode(((c & 31) << 6) | (c2 & 63));
            i += 2;
        } else {
            c2 = utftext.charCodeAt(i+1);
            c3 = utftext.charCodeAt(i+2);
            string += String.fromCharCode(((c & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63));
            i += 3;
        }
    }
    return string;
}


//启用禁用状态
export const StateStatus = {
  FREEZE: 0,
  ENABLED: 1
}
Object.freeze(StateStatus)

//格式化性别
export function fmGender(value) {
  let result = '女'
  if (value != 0) {
      result = '男'
  }
  return result
}

//订单状态
export const OrderStatusList = [
	{ key: 'CONFIRM', label: '待确认', value: 0},
	{ key: 'UN_PAID', label: '待支付', value: 10},
	{ key: 'IN_PAYMENT', label: '支付中', value: 15},
	{ key: 'PART_PAID', label: '部分支付', value: 18},
    { key: 'PAID', label: '已支付', value: 20},
    { key: 'REFUNDING', label: '退款中', value: 22},
	{ key: 'WAIT_GOODS', label: '待取货', value: 30},
	{ key: 'ARRIVED', label: '已到店', value: 35},
	{ key: 'PENDING', label: '待处理', value: 40},
	{ key: 'PROCESSING', label: '处理中', value: 45},
	{ key: 'DONE', label: '处理完成', value: 50},
	{ key: 'BACK_SHOP', label: '待发货', value: 52},
	{ key: 'DELIVERY', label: '待收货', value: 55},
	{ key: 'COMPLETED', label: '已完成', value: 60},
	{ key: 'CANCEL', label: '交易取消', value: 70},
    { key: 'REFUNDED', label: '已退款', value: 75}
]
// 优惠券类型
export const CouponTypeList = [
    { key: 'CASH', label: '满减券', value: 0},
    { key: 'DISCOUNT', label: '折扣券', value: 1},
    { key: 'FREE_WASH', label: '免洗券', value: 2},
    { key: 'EXPRESS', label: '运费券', value: 3}
]
export const WeekList = [
    {label:"周一",value:"1"},
    {label:"周二",value:"2"},
    {label:"周三",value:"3"},
    {label:"周四",value:"4"},
    {label:"周五",value:"5"},
    {label:"周六",value:"6"},
    {label:"周日",value:"7"},
]
//支付状态
export const PayMode = {
	'0': '未支付', //未支付
	PAID: 1, // 已支付,待处理 
	PROCESSING: 2, // 处理中  
	DONE: 3, // 已完成 
	CANCEL : 4 // 已取消
}

/**
 * 传入枚举集合和value,返回命中的枚举Label
 * @param e 枚举
 * @param value 值
 */
export function getEnumLabelByValue(e, value){
    if(e && value){
        let item = e.find(m=>m.value == value)
        if(item){
            return item.label;
        }
    }
    return null;
}
/**
 * 传入枚举集合和key,返回命中的枚举Label
 * @param e 枚举
 * @param key 值
 */
export function getEnumLabel(e, key){
    if(e && key){
        let item = e.find(m=>m.key == key)
        if(item){
            return item.label;
        }
    }
    return null;
}
/**
 * 传入枚举集合和key,返回命中的枚举Value
 * @param e 枚举
 * @param key 值
 */
export function getEnumValue(e, key){
    if(e && key){
        let item = e.find(m=>m.key == key)
        if(item){
            return item.value;
        }
    }
    return null;
}

/**
 * 价格显示格式化 1231元
 * @param money 价格值
 * @param precision 精度
 * @returns {string}
 */
export function fmPrice(money, precision = 0) {
    if(money === undefined || money === null || money.toString().replace(/^\s+|\s+$/g, '') === '') money = 0;
    let arr = (money+'').split('.');
    let isPrecision = arr.length > 1 && parseInt(arr[1]) > 0;
    if(typeof precision != 'number' || precision < 0){
        precision = 0;
    }
    if(isPrecision && precision > 0){
        money = parseFloat(money).toFixed(precision);
    }else{
        money = parseInt(money);
    }
    return money;
}
